package com.erlinyou.im.service.ofroster.Impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.erlinyou.base.service.BaseServiceImpl;
import com.erlinyou.im.dao.repository.chat.ChatMessageRepository;
import com.erlinyou.im.dao.repository.chat.ChatSessionRepository;
import com.erlinyou.im.dao.repository.ofroster.OfrosterRepository;
import com.erlinyou.im.model.ofroster.Ofroster;
import com.erlinyou.im.service.ofroster.OfrosterService;
@Service
public class OfrosterServiceImpl extends BaseServiceImpl<Ofroster, Long> implements OfrosterService {

	@Resource
	private ChatSessionRepository chatSessionRepository;
	
	@Resource
	private ChatMessageRepository chatMessageRepository;
	
	private OfrosterRepository repository;
	
	@Resource
	public void setBaseService(OfrosterRepository repository) {
		this.repository = repository;
		this.baseRepository = repository;
	}
	
	public List<Ofroster> findByUsernameAndSub(String userId,byte sub) {
		return repository.findByUsernameAndSub(userId,sub);
	}

	@Override
	public List<Ofroster> existsByCfrom(Long userId) {
		return repository.existsByCfrom(String.valueOf(userId));
	}

	@Override
	public Ofroster findByUsernameAndJid(String username, String jid) {
		return repository.findByUsernameAndJid(username, jid);
	}
	
	@Override
	public Ofroster findByUsernameAndJidNotSub(String username, String jid) {
		return repository.findByUsernameAndJidNotSub(username, jid);
	}
	
	@Override
	public <S extends Ofroster> List<S> saveAll(Iterable<S> entities) {
		return repository.saveAll(entities);
	}
	
	@Override
	public <S extends Ofroster> S save(S entity) {
		return baseRepository.save(entity);
	}

	@Transactional
	@Override
	public boolean delGoodFriend(Long userId, long rid,String gid) {
		int num = repository.deleteByUsernameAndJid(userId,rid);
		if(num>0) {
			int num1 = repository.deleteByUsernameAndJid(rid,userId);
			if(num1>0) {
				int num2 = chatSessionRepository.deleteByUseridAndRidAndCtype(userId,rid,1);
				if(num2>0) {
					int num3 = chatSessionRepository.deleteByUseridAndRidAndCtype(rid,userId,1);
					if(num3>0) {
						int byGid = chatMessageRepository.deleteByGid(gid);
						if(byGid>0) {
							return true;
						}else {
							throw new RuntimeException();
						}
					}else {
						throw new RuntimeException();
					}
				}else {
					throw new RuntimeException();
				}
			}else {
				throw new RuntimeException();
			}
		}else {
			throw new RuntimeException();
		}
	}

	@Override
	public List<Ofroster> findBySub(byte sub) {
		return repository.findBySub(sub);
	}
	
}
